<?php

/**
 * 微信登录
 * zc
 * 2018年11月7日09:54:28
 */
class Login extends MY_Controller
{
    function __construct()
    {
       parent::__construct();
       $this->load->model('Weixin/WeChat_model', 'wechat');
       $this->load->model('Weixin/Member_model', 'member');
    }

    /**
     * snsapi_base 静默授权 获取用户openid   进入回调页
     */
    function login_base()
    {
        $this->wechat->login_base();
    }

     /**
     * snapi_userinfo 获取用户基本信息  点击关注
     */
    function login_userInfo()
    {
       $this->wechat->login_userInfo();
    }

     /**
     * snsapi_base 静默授权 获取用户openid   进入回调页
     */
    function loginBaseBack()
    {
        if (!isset($_GET['code'])){
            //触发微信返回code码
            $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
            $url = $this->wechat->_CreateOauthUrlForCode($baseUrl);
            Header("Location: $url");
            exit();
        } else {
            //获取code码，以获取openid
            $code = $_GET['code'];
            $openid = $this->wechat->getOpenidFromMp($code);
            echo json_encode($openid);
        }
    }

    /**
     * snapi_userinfo 获取用户基本信息  点击关注
     */
    function loginUserInfoBack()
    {
        $get = $this->input->get();
        if (isset($get['code']) && $get['code']) 
        {
            $data = $this->login->getLoginAccess_token($get['code']);
            if (isset($data['access_token']) &&$data['access_token'] && isset($data['openid']) && $data['openid']) 
            {
                $data = $this->member->getUserInfo($data['openid']);
                if ($data['code'] == 0) 
                {
                    $data = $this->wechat->getUserInfo($data);
                    if (isset($data['openid']) && $data['openid'])
                    {
                        $this->member->addMember($data);
                    } else {
                        echo json_encode(array('code'=>0, 'mgs'=>'获取失败'));
                        exit;
                    }
                }
                setcookie('userinfo', serialize($data), time()+86400, '/');
                echo json_encode(array('code'=>1, 'data'=>$data));
            }
        }
    }
}